package com.example.flower_shop.controller;

import com.example.flower_shop.common.ApiResponse;
import com.example.flower_shop.dto.user.LoginRequest;
import com.example.flower_shop.dto.user.RegisterRequest;
import com.example.flower_shop.dto.user.UserVO;
import com.example.flower_shop.entity.User;
import com.example.flower_shop.service.UserService;
import com.example.flower_shop.service.JwtService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;

@Api(tags = "用户管理")
@Validated
@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;
    private final JwtService jwtService;
    private final PasswordEncoder passwordEncoder;

    @ApiOperation("用户注册")
    @PostMapping("/register")
    public ApiResponse<UserVO> register(
            @ApiParam("注册请求参数") @Valid @RequestBody RegisterRequest request) {
        try {
            // 检查用户名是否已存在
            if (userService.existsByUsername(request.getUsername())) {
                return ApiResponse.error("USERNAME_EXISTS", "用户名已存在");
            }

            // 检查手机号是否已存在
            if (userService.existsByPhone(request.getPhone())) {
                return ApiResponse.error("PHONE_EXISTS", "手机号已被使用");
            }

            // 创建用户
            User user = userService.register(
                    request.getUsername(),
                    request.getPassword(),
                    request.getPhone());

            // 生成token
            String token = jwtService.generateToken(user);

            return ApiResponse.success(new UserVO(user, token));
        } catch (Exception e) {
            return ApiResponse.error("REGISTER_FAILED", e.getMessage());
        }
    }

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public ApiResponse<UserVO> login(
            @ApiParam("登录请求参数") @Valid @RequestBody LoginRequest request) {
        try {
            System.out.println("开始处理登录请求: " + request.getUsername());

            // 查找用户
            User user = userService.findByUsername(request.getUsername())
                    .orElseThrow(() -> new RuntimeException("用户不存在"));

            System.out.println("找到用户: " + user.getUsername());
            System.out.println("用户角色: " + user.getRole());
            System.out.println("存储的密码: " + user.getPassword());
            System.out.println("输入的密码: " + request.getPassword());

            // 验证密码
            boolean passwordMatch = passwordEncoder.matches(request.getPassword(), user.getPassword());
            System.out.println("密码匹配结果: " + passwordMatch);

            if (!passwordMatch) {
                return ApiResponse.error("密码错误");
            }

            // 生成JWT token
            String token = jwtService.generateToken(user);
            System.out.println("生成的token: " + token);

            return ApiResponse.success(new UserVO(user, token));
        } catch (Exception e) {
            System.out.println("登录失败: " + e.getMessage());
            e.printStackTrace();
            return ApiResponse.error("LOGIN_FAILED", e.getMessage());
        }
    }

    @ApiOperation("获取当前用户信息")
    @GetMapping("/current")
    public ApiResponse<UserVO> getCurrentUser(
            @ApiParam(hidden = true) @AuthenticationPrincipal Long userId) {
        User user = userService.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户未登录"));

        return ApiResponse.success(new UserVO(user));
    }

    @ApiOperation("更新用户手机号")
    @PutMapping("/phone")
    public ApiResponse<UserVO> updatePhone(
            @ApiParam(hidden = true) @AuthenticationPrincipal Long userId,
            @ApiParam("手机号") @RequestParam @NotBlank(message = "手机号不能为空") String phone) {
        User user = userService.updatePhone(userId, phone);
        return ApiResponse.success(new UserVO(user));
    }
}